package com.example.mychat.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.mychat.entity.*;
import com.example.mychat.mapper.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Tag(name = "收发红包")
@Controller
@RequestMapping("/redpacket")
public class RedPacketController {
    @Autowired
    RedisTemplate redisTemplate;
    @Resource
    HttpServletRequest req;

    @Resource
    RedPacketMapper redPacketMapper;

    @Resource
    FriendMapper friendMapper;

    @Resource
    AuthoritiesMapper authoritiesMapper;

    @Operation(description = "发布红包")
    @PostMapping("")
    @ResponseBody
    public String publishRedPacket(@RequestParam int num, @RequestParam double amount) {
        String username = String.valueOf(req.getSession().getAttribute("username"));
        if (username.equals("null")) {
            return "用户未登录";
        }
        Redpacket redpacket = new Redpacket(username, -2, num, amount);
        redPacketMapper.insert(redpacket);
        int originId = redpacket.getId();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", username);
        Authorities authority = authoritiesMapper.selectOne(queryWrapper);
        int userId = authority.getId();
        queryWrapper.clear();
        queryWrapper.eq("userId", userId);
        queryWrapper.eq("groupId", 0);
        List<Friend> friendList = friendMapper.selectList(queryWrapper);
        for (Friend friend : friendList) {
            redPacketMapper.insert(new Redpacket(username, friend.getFriendId(), num, amount, originId));
        }
        redisTemplate.opsForValue().set(String.valueOf(originId), num);
        return "success";
    }

    @Operation(description = "抢红包")
    @GetMapping("/{id}")
    @ResponseBody
    public String getRedPacket(@PathVariable String id) {
        String username = String.valueOf(req.getSession().getAttribute("username"));
        if (username.equals("null")) {
            return "用户未登录";
        }
        if (redisTemplate.opsForHash().hasKey(username, id)) {
            return "已经抢过该红包";
        }
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.watch(id);
        int remainingNum = (int) redisTemplate.opsForValue().get(id);
        if (remainingNum > 0) {
            redisTemplate.multi();
            redisTemplate.boundValueOps(id).decrement(1);
            List<Object> objects = redisTemplate.exec();
            if (objects == null || objects.size() == 0) {
                return "failure";
            }
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", Integer.valueOf(id));
            Redpacket redpacket = redPacketMapper.selectOne(queryWrapper);
            redpacket.setRedPacketNum((int) redisTemplate.opsForValue().get(id));
            redPacketMapper.update(redpacket, queryWrapper);
            redisTemplate.opsForHash().put(username, id, redpacket.getRedPacketAmount());
            return "success";
        } else {
            return "empty";
        }
    }
}
